from django.shortcuts import render
from django.views.generic import View
from .models import NewsChannel, Article
from django.http import HttpResponseNotFound
from django.core.paginator import Paginator, EmptyPage
# Create your views here.


class IndexView(View):
    def get(self, request, channel_id=1, page_num=1):
        """新闻列表展示功能"""
        try:
            # 获取频道对象
            newschannel = NewsChannel.objects.get(id=channel_id)
        except NewsChannel.DoesNotExist:
            return HttpResponseNotFound('未找到频道id！！')
        else:
            # 获取当前频道下的所有类别id
            category_id_list = [category.id for category in newschannel.newscategory_set.all() if category]
        # 获取当前频道下的所有id
        articles = Article.objects.filter(category_id__in=category_id_list).order_by('id')

        # 创建一个分页器对象
        page_obj = Paginator(articles, 3)

        try:
            page_article = page_obj.page(page_num)
        except EmptyPage:
            return HttpResponseNotFound('未找到当前页面！！')

        return render(request, 'newsapp/index.html', {'articles': page_article, 'channel_id': channel_id})


class DetailView(View):
    def get(self, request, article_id):
        """
        新闻详情
        :param request:
        :param article_id:
        :return:
        """
        try:
            article = Article.objects.get(id=article_id)
        except Article.DoesNotExist:
            return HttpResponseNotFound('未找到该文章详情！！')
        return render(request, 'newsapp/detail.html', {'article': article})
